<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { LowcodeTableConfigApi } from '#/api/lowcode/table-config';
import type { LowcodeDatasourceApi } from '#/api/lowcode/datasource';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { Page, useVbenModal } from '@vben/common-ui';
import { isEmpty } from '@vben/utils';

import { message } from 'ant-design-vue';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteTableConfig,
  deleteTableConfigList,
  getTableConfigPage,
  syncCodegenFromDB,
} from '#/api/lowcode/table-config';
import { getDatasourceConfigPage } from '#/api/lowcode/datasource';
import { $t } from '#/locales';

import { useGridColumns, useGridFormSchema } from './data';
import ImportTable from './modules/import-table.vue';
import QuickGenerator from '#/views/lowcode/generic/components/QuickGenerator.vue';

const router = useRouter();
const dataSourceConfigList = ref<LowcodeDatasourceApi.DatasourceConfig[]>(
  [],
);

/** 获取数据源名称 */
const getDataSourceConfigName = (dataSourceConfigId: number) => {
  // 如果是0或未设置，返回默认数据源
  if (!dataSourceConfigId || dataSourceConfigId === 0) {
    return '默认数据源(master)';
  }
  
  return dataSourceConfigList.value.find(
    (item) => item.id === dataSourceConfigId,
  )?.name;
};

const [ImportModal, importModalApi] = useVbenModal({
  connectedComponent: ImportTable,
  destroyOnClose: true,
});

const quickGeneratorRef = ref<InstanceType<typeof QuickGenerator>>();

/** 刷新表格 */
function onRefresh() {
  gridApi.query();
}

/** 导入表格 */
function handleImport() {
  importModalApi.open();
}


/** 编辑表格 */
function handleEdit(row: LowcodeTableConfigApi.CodegenTable) {
  router.push({ name: 'LowcodeTableConfigEdit', query: { id: row.id } });
}

/** 删除代码生成配置 */
async function handleDelete(row: LowcodeTableConfigApi.CodegenTable) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.tableName]),
    duration: 0,
    key: 'action_process_msg',
  });
  try {
    await deleteTableConfig(row.id);
    message.success($t('ui.actionMessage.deleteSuccess', [row.tableName]));
    onRefresh();
  } finally {
    hideLoading();
  }
}

const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
  records,
}: {
  records: LowcodeTableConfigApi.CodegenTable[];
}) {
  checkedIds.value = records.map((item) => item.id);
}

/** 批量删除代码生成配置 */
async function handleDeleteBatch() {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting'),
    duration: 0,
    key: 'action_process_msg',
  });
  try {
    await deleteTableConfigList(checkedIds.value);
    checkedIds.value = [];
    message.success($t('ui.actionMessage.deleteSuccess'));
    onRefresh();
  } finally {
    hideLoading();
  }
}

/** 同步数据库 */
async function handleSync(row: LowcodeTableConfigApi.CodegenTable) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.updating', [row.tableName]),
    key: 'action_key_msg',
  });
  try {
    await syncCodegenFromDB(row.id);
    message.success({
      content: $t('ui.actionMessage.updateSuccess', [row.tableName]),
      key: 'action_key_msg',
    });
    onRefresh();
  } finally {
    hideLoading();
  }
}

/** 生成通用页面 */
function handleGeneratePage(row: LowcodeTableConfigApi.CodegenTable) {
  // 构建通用页面URL
  const url = `/lowcode/generic?tableName=${row.tableName}&configId=${row.id}&dataSourceId=${row.dataSourceConfigId || 0}`;
  
  // 在新标签页中打开
  window.open(url, '_blank');
  
  message.success(`已为表 "${row.tableName}" 生成通用管理页面`);
}

/** 打开快速生成器 */
function handleQuickGenerate() {
  quickGeneratorRef.value?.open();
}


const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    columns: useGridColumns(getDataSourceConfigName),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getTableConfigPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<LowcodeTableConfigApi.CodegenTable>,
  gridEvents: {
    checkboxAll: handleRowCheckboxChange,
    checkboxChange: handleRowCheckboxChange,
  },
});

/** 获取数据源配置列表 */
async function initDataSourceConfig() {
  try {
    const result = await getDatasourceConfigPage({
      pageNo: 1,
      pageSize: 1000, // 获取所有数据源用于下拉选择
    });
    dataSourceConfigList.value = result.list || [];
  } catch (error) {
    console.error('获取数据源配置失败', error);
  }
}

/** 初始化 */
initDataSourceConfig();
</script>
<template>
  <Page auto-content-height>
    <ImportModal @success="onRefresh" />
    <QuickGenerator ref="quickGeneratorRef" @success="onRefresh" />
    <Grid table-title="表配置列表">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: '新建',
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['infra:codegen:create'],
              onClick: handleImport,
            },
            {
              label: '快速生成',
              type: 'primary',
              icon: ACTION_ICON.PLAY,
              auth: ['infra:codegen:preview'],
              onClick: handleQuickGenerate,
            },
            {
              label: $t('ui.actionTitle.import'),
              type: 'default',
              icon: ACTION_ICON.IMPORT,
              auth: ['infra:codegen:create'],
              onClick: handleImport,
            },
            {
              label: '批量删除',
              type: 'primary',
              danger: true,
              disabled: isEmpty(checkedIds),
              icon: ACTION_ICON.DELETE,
              auth: ['infra:codegen:delete'],
              onClick: handleDeleteBatch,
            },
          ]"
        />
      </template>
      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: $t('common.edit'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              auth: ['infra:codegen:update'],
              onClick: handleEdit.bind(null, row),
            },
            {
              label: '同步',
              type: 'link',
              icon: ACTION_ICON.SYNC,
              auth: ['infra:codegen:update'],
              onClick: handleSync.bind(null, row),
            },
            {
              label: '生成页面',
              type: 'link',
              icon: ACTION_ICON.VIEW,
              auth: ['infra:codegen:preview'],
              onClick: handleGeneratePage.bind(null, row),
            },
            {
              label: $t('common.delete'),
              type: 'link',
              danger: true,
              icon: ACTION_ICON.DELETE,
              auth: ['infra:codegen:delete'],
              popConfirm: {
                title: $t('ui.actionMessage.deleteConfirm', [row.tableName]),
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
